package com.SpringBoot.mail;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.SpringBoot.Util.RedisService;
import com.SpringBoot.Util.Result;
import com.SpringBoot.mail.pojo.Mail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MailService {

    @Autowired
    private Mail mail;
    @Autowired
    private RedisService redisService;

    public Result sendMail(String email) {
        // 配置邮箱账户
        MailAccount account = new MailAccount();
        account.setHost(mail.getHost());
        account.setPort(mail.getPort());
        account.setFrom(mail.getFrom());
        account.setUser(mail.getUsername());
        account.setPass(mail.getPassword());
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(1000000));

        String subject = "验证码";
        String content = "您的验证码是：" + code + "，请在5分钟内使用。";
        try {
            MailUtil.send(account, email, subject, content, false);
            //存入redis
            redisService.setCacheObject("mail:code:" + email, code, 5, TimeUnit.MINUTES);

            return Result.success("发送成功"); // 可以返回验证码给前端，也可以只返回成功
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(404,"邮件发送失败：" + e.getMessage());
        }
    }

    public Result verifyCode(String email, String code) {
        String redisCode = redisService.getCacheObject("mail:code:" + email);
        if(code == null || code.trim().isEmpty()){
            return Result.error(400,"验证码不能为空");
        }
        if(redisCode == null){
            return Result.error(400,"验证码已过期，请重新获取");
        }
        if(!code.equals(redisCode)){
            return Result.error(401,"验证码错误");
        }
        redisService.deleteObject("mail:code:" + email);
        return Result.success("验证码正确");
    }
}
